package com.imti.xmlparserdemo;

import android.text.TextUtils;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAXHelper extends DefaultHandler
{

    private static final String TAG = SAXHelper.class.getSimpleName();

    private List<StudentModel> dataList;

    private StudentModel student;

    private String tagName;

    public List<StudentModel> getDataList()
    {
        return dataList;
    }

    @Override
    public void startDocument() throws SAXException
    {
        super.startDocument();

        dataList = new ArrayList<>();
    }
    @Override
    public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException
    {
        super.startElement(uri, localName, qName, attributes);

        tagName = localName;

        if (localName.equals("student"))
        {
            student = new StudentModel();
            student.setId(attributes.getValue("id"));
        }
    }
    @Override
    public void characters(char[] ch, int start, int length) throws SAXException
    {
        super.characters(ch, start, length);

        if (!TextUtils.isEmpty(tagName))
        {
            switch (tagName)
            {
                case "name":
                    student.setName(new String(ch, start, length));
                    break;

                case "age":
                    student.setAge(new String(ch, start, length));
                    break;
            }
        }
    }

    @Override
    public void endElement(String uri, String localName, String qName) throws SAXException
    {
        super.endElement(uri, localName, qName);

        if (localName.equals("student"))
        {
            dataList.add(student);

            student = null;
        }

        tagName = null;
    }
    @Override
    public void endDocument() throws SAXException
    {
        super.endDocument();

        Log.d(TAG, "XML 数据解析完成");
    }
}
